<link rel="import" href="/components/polymer/polymer.html">
<link rel="import" href="/components/core-ajax/core-ajax.html">

<polymer-element name="nav-service" attributes="navs">
  <template>
    <style>
    :host {
      display: none;
    }
    </style>
    <core-ajax id="ajax"
      auto
      url="navs.json"
      on-core-response="{{navsLoaded}}"
      handleAs="json">
    </core-ajax>
  </template>
  <script>
  Polymer('nav-service', {
    created: function() {
      this.navs = [];
    },

    navsLoaded: function() {
      // Make a copy of the loaded data
      this.navs = this.$.ajax.response.slice(0);

      //add active and selected support
      this.add_property(this.navs);

      //set spec url highlight
      var url = location.pathname;
      url = this.rm_back(url);
      var p = this.find_papa(this.navs,url);
      if(p[0].length>0){
        for(var i = 0; i < p[0].length-1; i++){
          p[0][i].active = true;
        }
        p[0][p[0].length-1].active = true;
        p[0][p[0].length-1].selected = p[1];
      }else if(p[1]!=""){
        this.navs.selected=p[1];
      }
    },

    //according to url to find a parents list in navs
    find_papa: function(navs,url){
      var papa = [];
      for(var i = 0; i < navs.length; i++){
      	if(navs[i].children){
	        var p = this.find_papa(navs[i].children,url);
	        if(p[1]!=""){
	          papa.push(navs[i]);
	          if(p[0].length!=0){
              for(var j = 0; j < p[0].length; j++){
	      	      papa.push(p[0][j]);
	            }
	          }
	          return [papa,p[1]];
	        }
	      }else{
	        var t_url = this.rm_back(navs[i].url);
	        if(url == t_url){
	          return [papa,i+""];
	        } 
	      }
      }
      return [papa,""];
    },

    //add active and selected support
    add_property: function(navs){
      navs.selected="";
      for(var i = 0; i < navs.length; i++){
      	if(navs[i].children){
          navs[i].active=false;
          navs[i].selected="";
	        this.add_property(navs[i].children);
	      }
      }
    },

    //remove url's last '/'
    rm_back: function(str){
      str = str.trim();
      var i = str.lastIndexOf('/');
      return (i+1==str.length)?str.substring(0,i):str;
    }
  });
  </script>
</polymer-element>

